﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace Nsf.Samples.RetryActivitySample.Infrastructure.Actions
{
    public class ActionManager
    {
        private readonly Dictionary<String, ActionSummaryEx> _actions;

        public ActionManager()
        {
            _actions = new Dictionary<String, ActionSummaryEx>(StringComparer.InvariantCultureIgnoreCase);
        }

        public void RegisterAction<TAction>(String command) where TAction : IAction
        {
            if (command == null)
                throw new ArgumentNullException("command");
            if (_actions.ContainsKey(command))
                throw new ArgumentException("Command is already registered", "command");
            var actionAttribute = typeof (TAction).GetCustomAttributes(typeof (ActionAttribute), false).Cast<ActionAttribute>().FirstOrDefault();
            var actionSummary = new ActionSummaryEx() {ActionType = typeof (TAction), Command = command};
            if (actionAttribute != null)
            {
                actionSummary.Name = actionAttribute.Name;
                actionSummary.Description = actionAttribute.Description;
            }
            _actions.Add(command, actionSummary);
        }

        public IList<ActionSummary> GetRegisteredActions()
        {
            return (from action in _actions.Values
                    select new ActionSummary(action)).ToList();
        }

        public Boolean TryCreateAction(String command, out IAction action)
        {
            if (command == null)
                throw new ArgumentNullException("command");
            action = default(IAction);
            ActionSummaryEx actionSummary;
            if (!_actions.TryGetValue(command, out actionSummary))
                return false;
            action = (IAction) Activator.CreateInstance(actionSummary.ActionType);
            return true;
        }



    }
}
